package com.jmx;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

public class LogWriter {

	private static final Logger logger = Logger.getLogger(LogWriter.class);
	private static final String FILENAME = "/invoke_times.properties";
	private PropertiesWrapper propertiesWrapper;
	
	public LogWriter() {
		
	}
	
	public synchronized void writeCountToProperties(String name) {
		propertiesWrapper = new PropertiesWrapper(FILENAME);
		String value = propertiesWrapper.getProperty(name);
		int iValue = 0;
		if(value != null) {
			iValue = Integer.parseInt(value);
		}
		propertiesWrapper.updateProperty(name, Integer.toString(iValue + 1), "Invoke times");
	}
	
	private void writeHugeLog() throws Exception {
		int length = 0x8FFFFFF;// 128 MB
		String info = "[2012-06-12 15:50:58,706 INFO ] [http-8443-1] core.interceptor.ExceptionHandler.doAroundExposeService(108) - Message Id is 60825414-eb3a-4e6f-b5f2-0f2241c66c9b. End invoke service com.security.dpi.bds.helloworld.service.impl.HelloWorldExposeServiceImpl.hello";
		FileChannel fc = new RandomAccessFile("test.log", "rw").getChannel();
		MappedByteBuffer out = fc.map(FileChannel.MapMode.READ_WRITE, 0, length);
		for (int i = 0; i < length/info.length(); i++) {
			for(byte byteInfo : info.getBytes()) {
				out.put(byteInfo);
			}
			out.put((byte)'\n');
		}
		System.out.println("Finished writing");
		for (int i = length / 2; i < length / 2 + 6; i++)
			System.out.print((char) out.get(i));
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		final LogWriter logWriter = new LogWriter();
		Runnable runnable = new Runnable() {
			public void run() {
				logWriter.writeCountToProperties("com.jmx.HelloWorld");
			}
		};
		ExecutorService executorService = Executors.newFixedThreadPool(5);
		for(int i = 0; i < 10; i++) {
			executorService.execute(runnable);
		}
		Thread.sleep(3000);
		executorService.shutdownNow();
	}

}
